<template>
  <div class="message">
    <div class="block">
      <h2>留言板</h2>
      <p>请文明发言，禁止广告。不然拉黑了嗷😂\(^o^)/~</p>
      <div class="inputText">
        <el-form>
          <el-form-item>
            <el-input
              type="textarea"
              :rows="3"
              placeholder="请输入内容"
              v-model="textarea"
              maxlength="100"
              show-word-limit
            >
            </el-input>
          </el-form-item>
        </el-form>
      </div>
      <div class="emojiBox">
        <Emoji @addEmoji="addEmoji" />
        <el-button type="primary" size="mini" @click="sendMessage"
          >发送留言</el-button
        >
      </div>
    </div>
    <div class="block2">
      <ul v-if="messageData && messageData.length > 0">
        <li v-for="(item, i) in messageData" :key="i">
          <!-- 一级评论区 -->
          <div class="comment">
            <img :src="baseUrl + item.author.photo" alt="" />
            <div class="comment_info">
              <div class="name_time">
                <span :class="{ active: userInfo._id == item.author._id }">{{
                  item.author.username
                }}</span>
                <span>{{ formatDate(item.date) }}</span>
              </div>
              <p>{{ item.content }}</p>
              <div class="like_reply">
                <i
                  class="iconfont icon-xinaixin"
                  :class="{
                    active: userInfo._id && item.likes.includes(userInfo._id), //当前用户是否点赞
                  }"
                  @click="commentLikes(item._id)"
                >
                </i>
                <span>{{ item.likes.length }}</span>
                <i
                  v-if="!(userInfo._id == item.author._id)"
                  class="iconfont icon-huifu"
                  @click="commentReply(item)"
                ></i>
              </div>
            </div>
          </div>

          <!-- 回复(子级/二级) -->
          <div
            class="comment reply"
            v-for="(childItem, i) in item.children"
            :key="i"
          >
            <img :src="baseUrl + childItem.author.photo" alt="" />
            <div class="comment_info">
              <div class="name_time">
                <span
                  :class="{ active: userInfo._id == childItem.author._id }"
                  >{{ childItem.author.username }}</span
                >
                <span>{{ formatDate(childItem.date) }}</span>
              </div>
              <p>
                <span>@{{ childItem.replyId.username }}</span
                >{{ childItem.content }}
              </p>
              <div class="like_reply">
                <i
                  class="iconfont icon-xinaixin"
                  :class="{
                    active:
                      userInfo._id && childItem.likes.includes(userInfo._id), //当前用户是否点赞
                  }"
                  @click="replyLikes(item._id, childItem._id, i)"
                >
                </i>
                <span>{{ childItem.likes.length }}</span>
                <i
                  v-if="!(userInfo._id == childItem.author._id)"
                  class="iconfont icon-huifu"
                  @click="childReply(item, childItem)"
                ></i>
              </div>
            </div>
          </div>

          <!-- 回复框 -->
          <div class="reply_input" :class="{ show: item.isShowReply }">
            <el-input
              :placeholder="'@' + item.author.username"
              v-model="item.replyContent"
              size="mini"
              clearable
            >
            </el-input>
            <div class="emojiBox" style="margin-top: 5px">
              <Emoji @addEmoji="addEmoji" :msgdata="item._id" />
              <el-button type="primary" size="mini" @click="replySubmit(item)"
                >提交回复</el-button
              >
            </div>
          </div>
        </li>
      </ul>
      <el-empty v-else description="暂无友链"></el-empty>
    </div>
  </div>
</template>

<script>
import { mapState } from "vuex";
import Emoji from "./compontents/Emoji.vue";
export default {
  name: "message",
  components: {
    Emoji,
  },
  data() {
    return {
      textarea: "",
      isShowEmoji: false,
      messageData: null,
    };
  },
  computed: {
    ...mapState(["userInfo"]),
  },
  methods: {
    // 添加表情
    addEmoji(data, id) {
      if (this.textarea.length > 99) return;
      if (!id) return (this.textarea += data);
      this.messageData.forEach((val, i) => {
        if (val._id == id) {
          if (val.replyContent > 99) return;
          val.replyContent += data;
        }
      });
    },
    // 发送留言
    async sendMessage() {
      // 判断用户是否登录
      if (!this.userInfo.username)
        return this.$message.error("登录后才能发表留言");
      let msgVal = this.textarea.trim();
      if (!msgVal) return this.$message.error("内容不能为空");

      let { data } = await this.$axios({
        method: "POST",
        url: "/msg/sendMsg",
        data: { msgVal },
      });
      if (data.code) return this.$message.error(data.message);
      this.$message.success(data.message);
      this.textarea = "";
      this.getMsgData();
    },

    // 获取评论数据
    async getMsgData() {
      let { data } = await this.$axios({
        method: "GET",
        url: "/getData/getMsgData",
      });
      if (data && data.data && data.data.length > 0) {
        data.data.forEach((item) => {
          //这一层的遍历都是对 一级评论进行遍历
          item.isShowReply = false; //控制当前这条评论下的回复框显示 / 隐藏
          item.replyContent = ""; //控制当前评论下的回复input框里的内容
          item.replyUser = item.author; //子级的父级作者id
        });
      }

      this.messageData = data.data;
    },
    // 时间格式
    formatDate(date) {
      let d = new Date(date),
        YY = d.getFullYear(),
        MM = d.getMonth() + 1,
        DD = d.getDate(),
        hh = d.getHours(),
        mm = d.getMinutes(),
        ss = d.getSeconds();
      return `${YY}-${MM}-${DD} ${hh}:${mm}:${ss}`;
    },

    // 评论点赞
    async commentLikes(id) {
      if (!this.userInfo.username) return this.$message.error("请先登录");

      let { data } = await this.$axios({
        method: "POST",
        url: "/msg/comment/likes",
        data: { id },
      });
      if (data.code) return this.$message.error(data.message);
      this.getMsgData();
    },
    //子集评论点赞
    async replyLikes(parentId, childId, childIndex) {
      //判断用户是否登录
      if (!this.userInfo.username) return this.$message.error("请先登录");
      //提交数据
      let { data } = await this.$axios({
        method: "POST",
        url: "/msg/like/replay",
        data: { parentId, childId, childIndex },
      });
      if (data.code) return this.$message.error(data.message); //回复失败
      this.getMsgData(); //重新获取最新的留言数据
    },

    //点击父级评论的回复按钮：显示 / 隐藏   回复框
    commentReply(item) {
      // 判断用户是否登录
      if (!this.userInfo.username) return this.$message.error("请先登录");
      //判断一级评论的作者 是否 不等于 存储里的replyUser里的用户id， 点开
      if (item.author._id !== item.replyUser._id) {
        item.isShowReply = true;
      } else {
        item.isShowReply = !item.isShowReply; //点击显示/隐藏
      }
      //修改@后面的名字。  修改一级评论对象里的replayUser = 父评论的作者数据
      item.replyUser = item.author;
    },

    // 回复提交
    async replySubmit(item) {
      // 判断用户是否登录
      if (!this.userInfo.username) return this.$message.error("登录后才能回复");
      let content = item.replyContent.trim();
      if (!content) return this.$message.error("请输入回复的内容！");
      if (content.length > 100) return this.$message.error("字数不能超过100");

      let { data } = await this.$axios({
        method: "POST",
        url: "/msg/comment/reply",
        data: {
          id: item._id, //被评论的评论id
          content, //回复的内容
          replyId: item.replyUser._id, //父级评论的作者id， a回复的b，这是b的id
        },
      });
      if (data.code) return this.$message.error(data.message); //回复失败
      this.$message.success(data.message); //回复成功
      this.getMsgData(); //重新获取所有的留言数据
    },
    // 子集回复提交
    childReply(item, childItem) {
      //判断用户是否登录
      if (!this.userInfo.username) return this.$message.error("请先登录");
      //判断，当前点击了按钮的作者 是否 与  所在的一级评论的作者不相同
      if (childItem.author._id !== item.replyUser._id) {
        item.isShowReply = true;
      } else {
        item.isShowReply = !item.isShowReply; //点击显示/隐藏
      }
      //点击时，设置一级评论对象里的replyUser =  子评论的作者（我要@的用户）
      item.replyUser = childItem.author;
    },
  },
  created() {
    this.getMsgData();
  },
  mounted() {},
};
</script>

<style lang="less" scoped>
.message {
  width: 100%;
  .emojiBox {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .block {
    user-select: none;
    background: #fff;
    padding: 20px;
    margin-bottom: 20px;
    h2 {
      margin-bottom: 15px;
      font-size: 20px;
      letter-spacing: 3px;
      line-height: 24px;
      border-left: 5px solid #73b899;
      text-indent: 10px;
    }
    p {
      text-indent: 2em;
      color: #444;
      font-size: 14px;
      letter-spacing: 4px;
      line-height: 30px;
    }
    .inputText {
      margin: 15px 0;
    }
  }
  .block2 {
    background: #fff;
    padding: 20px;
    > ul li {
      padding-bottom: 5px;
      margin-bottom: 10px;
      border-bottom: 1px dashed #ddd;
      font-size: 12px;
      .comment {
        display: flex;
        img {
          width: 40px;
          height: 40px;
          margin-right: 15px;
          border-radius: 50%;
        }
        .comment_info {
          .name_time {
            span {
              font-size: 12px;
              color: #666;
              opacity: 0.8;
              margin-right: 15px;
              &:first-child {
                font-size: 14px;
                color: #666;
              }
              &.active {
                color: lightcoral;
              }
            }
          }
          p {
            font-size: 12px;
            color: #666;
            letter-spacing: 2px;
            word-break: break-word;
            line-height: 20px;
            padding: 10px 0;
            span {
              letter-spacing: 0;
              font-size: 14px;
              color: rgb(124, 211, 240);
              padding: 0 5px;
            }
          }
          .like_reply {
            color: #aaa;
            margin-bottom: 20px;
            i {
              cursor: pointer;
              font-size: 14px;
            }

            span {
              font-size: 12px;
              margin-right: 40px;
            }
            > .active {
              color: red;
            }
          }
        }
      }
      .comment.reply {
        margin: 10px 8px 8px 55px;
      }
      .reply_input {
        overflow: hidden;
        width: 100%;
        height: 0;
        padding-left: 55px;
        box-sizing: border-box;
        transition: 0.2s;
        text-align: right;
        &.show {
          overflow: visible;
          height: 70px;
        }
      }
    }
  }
}
</style>